%% modeFinderMain.m 
%  Last revision 2/25/2014 1:31 PM  AJ 

%% 1. Load settings from loadPath
location.loadPath=...
    cr_dirpath(cucd,location.root,location.specification,...
    location.subfolder);

cd(location.loadPath);

if isempty(location.settingsFile);
    settings;
    location.settingsFile='settings';
else
    eval(location.settingsFile);
end
cd(cucd);
disp('Loaded settings');
%% 2. Load priors and initial parameter
%  modeFinderShell: this is still a mess and needs to be cleaned
pause(1); 
disp('Loading Prior and Parameters'); 
modeFinderShell;   
clear ii ans temp parnames4; 

%% 3. Check flags, assign functions for likelihood and filter 
modeFinderFlags; 


%% 4. Load data with dataStru and update sampleStru 
modeFinderData; 

tempNames=extractObsNames(ZZ(:,:,1),stateNames); 
printcell([tempNames Ynames(:)]); 
if flags.onscreen==1 
   quer('c'); 
end 
clear tempNames; 

%% 4.a Output used by the Chicago model codes 
model.steady=ssvec; 
model.addsol=addsol; 
model.handleFilter=addsol.funcKfilter; 
model.data=Y; 
model.trainVec=trainvec; 
model.path=location.savePath; 
model.solveOptions=solveopt; 


%% 5. Two important checks 

%% 5.a changeHandle 
% If model handle to be changed, check models are identical      
if flags.changeHandle==true
    if flags.initialCond==1
        disp('Cannot change handle if initial condition is used')
    else
        disp('Checking handle change');
        handleChange(model.add2Handle,model.handle,...
            prpar.mean,solveopt,addsol);
    end 
    %% Use tempHandle to check the report
    if flags.onscreen==1 
        quer('c'); 
    end 
end     

%% 5.b checkReport 
%  Check all variables requested in report exist  
if flags.checkReport==1
    disp('Begin checking report....');
    [report,flags]=...
        reportCheck(report,model,paramToTest,flags,sampleStru);
end

%% 6. Fix Seed for Random values 
if isfield(priorStru,'seedNum')==false || ...
        isempty(priorStru.seedNum)==true 
    priorStru.seedNum=sum(100*clock); 
end 
RandStream.setGlobalStream(RandStream.create('mt19937ar','seed',priorStru.seedNum));

%% 7. Start Parallelization 
%     This will need to be modified as you move to your own servers 
if flags.parallel==1
    modeFinderSetParallel;
end


%% 8. names 
% Junk below should be organized into the structure names 
% together with statenames, etc. 
shonames=shockNamesStru.short; 
znames=cell(size(ZZ,1),1);
pos_obsinstates=zeros(length(znames),1); 
for ii=1:length(znames)
    temp      =find(ZZ(ii,:,1)~=0 ) ;
    if length(temp) > 1
        error('Need 1 entry only for each row of ZZ')
    end
     znames(ii)=stateNames( temp );
     pos_obsinstates(ii)=temp; 
end 
disp('Observables'); 
printcell([znames(:) Ynames(:)]); 
%quer('c'); 
clear junk znames initss; 
clear CONS GG RR SDX ans eu ii paramToTest; 
%%=============================================================

%% 9. Generate starting values 
modeFinderInitialize;


%% 10. Maximize Posterior or Likelihood
% There is an inner loop depending on whether 
%  the code is run in parallel or single 
modeFinderLoopOuter; 


%% 11. Generate Output 
% Assign Flags to ensure all output is created 
flags.hessianDone=0; 
flags.spectrumDone=0; 
flags.tableDone=0; 
flags.handleChanged=0; 
cd(location.savePath); 
save workspace;
cd(cucd); 

modeFinderOutput; 

%% 12. Close parallel pool and quit 
if flags.parallel==1
    delete(gcp)
    disp('Closed workers') 
end


